package com.weng.platform.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.framework.common.model.component.tree.TreeGridBuilder;
import com.weng.framework.common.model.component.tree.TreeNode;
import com.weng.framework.core.constants.ResultCodeEnum;
import com.weng.framework.core.exception.GlobalServiceException;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import com.weng.framework.dao.mybatis.service.BaseServiceImpl;
import com.weng.platform.platform.entity.Column;
import com.weng.platform.platform.mapper.ColumnMapper;
import com.weng.platform.platform.model.vo.ColumnTreeNode;
import com.weng.platform.platform.service.IColumnService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;


/**
 * 栏目 服务实现类
 *
 * @author wenghui
 * @date 2019-11-29 14:48:01
 *
 */
@Slf4j
@Service
public class ColumnServiceImpl extends BaseServiceImpl<ColumnMapper, Column> implements IColumnService {
		@Autowired
		private ColumnMapper columnMapper;


		/*
		 * 通过栏目Id，获取所有子栏目的Id，包括自己的
		 * @param [id]
		 * @return
		 */
		public List<String> getAllChildIds(String id){
				List<String> ids = new ArrayList<>();
				ids.add(id);
				Column column = this.columnMapper.selectById(id);
				if(column != null && StringUtils.isNotEmpty(column.getType())){
						// 通过栏目类型，分组给每个父Id找出对应的子Id
						Map<String,List<String>> idsByParentMap = getAllGroupByParentId(column.getType());
						findChildIds(id, idsByParentMap, ids);
				}
				return ids;
		}

		/**
		 * 循环寻找子节点
		 * @param pId
		 * @param allCIdsByPids
		 * @param result
		 */
		public void findChildIds(String pId,Map<String,List<String>> allCIdsByPids,List<String> result){
				if(allCIdsByPids.containsKey(pId)){
						List<String> cIds = allCIdsByPids.get(pId);
						for(String cid : cIds){
								result.addAll(cIds);
								findChildIds(cid, allCIdsByPids, result);
						}
				}
		}

		/*
		 * 通过栏目类型，分组给每个父Id找出对应的子Id
		 * @param [type 栏目类型]
		 * @return
		 */
		private Map<String,List<String>> getAllGroupByParentId(String type){
				Map<String,List<String>> pidMap = new HashMap<>();
				List<Column> allColumns =  getAllIdAndParentIdByType(type);
				if(allColumns!=null){
						for(Column obj :allColumns){
								String pId = obj.getParentId();
								String cId = obj.getId();
								if(pidMap.containsKey(pId)){
										List<String> childIds = pidMap.get(pId);
										childIds.add(cId);
								}else{
										List<String> childIds = new ArrayList<>();
										childIds.add(cId);
										pidMap.put(pId, childIds);
								}
						}
				}

				return pidMap;
		}

		private List<Column> getAllIdAndParentIdByType(String type){
				QueryWrapper<Column> wrapper = new QueryWrapper<>();
				wrapper.select("id","parent_id");
				wrapper.eq("type",type);
				wrapper.eq("is_del",0);
				return  this.columnMapper.selectList(wrapper);
		}

		@Override
		public List<ColumnTreeNode> getTreeGridData(String name, String code, String parentId, String isExpand
						, String type, String ownerId) {

				Column column = new Column();
				QueryWrapper<Column> wrapper = new QueryWrapper<>();
				wrapper.eq("type",type);
				wrapper.eq("owner_id",ownerId);
				if(!StringUtils.isEmpty(name)){
						wrapper.like("name", name);
				}
				if(!StringUtils.isEmpty(code)){
						wrapper.like("code", code);
				}
				wrapper.orderByAsc("position");
				List<Column> data = columnMapper.selectList(wrapper);
				List<ColumnTreeNode> list = new TreeGridBuilder<Column, ColumnTreeNode>(data)
								.build(new ColumnComparator(),new ColumnTreeNode(), false);
				if ("1".equals(isExpand)) {
						TreeNode.expandAllNodes(list);
				}
				TreeNode.expandNodesByDepth(list,2);
				return list;
		}

		private class ColumnComparator implements Comparator<Column> {
				@Override
				public int compare(Column o1, Column o2) {
						Double depth1 = o1.getPosition();
						Double depth2 = o2.getPosition();
						if(depth1==null || depth2==null){
								return 0;
						}else {
								return o1.getPosition().intValue() - o2.getPosition().intValue();
						}
				}
		}

		/**
		 * 分页查询栏目
		 * @return
		 */
		@Override
		public IPage<Column> list(Integer pageNo,Integer pageSize, String ownerId) {
				QueryWrapper<Column> qw = new QueryWrapper<>();
				qw.eq("owner_id", ownerId);
				IPage<Column> page = new PageModel<>(pageNo,pageSize);

				return columnMapper.selectPage(page,qw);
		}


		/**
		 * 获取单个栏目
		 * @param code
		 * @return
		 */
		@Override
		public Column  findByCode(String code) {
				QueryWrapper<Column> qw = new QueryWrapper<Column>();
				qw.eq("code",code);
				List<Column> list = columnMapper.selectList(qw);
				if(list != null && list.size()>0){
						return list.get(0);
				}
				return null;
		}

		/**
		 * 获取单个栏目
		 * @param id
		 * @return
		 */
		@Override
		public Column getById(Serializable id) {
				return super.getById(id);
		}



		/**
		 * 新增单个栏目
		 * @param column
		 * @return
		 */
		@Override
		public Column add(Column column) throws GlobalServiceException {

				columnMapper.insert(column);
				return column;
		}

		/**
		 * 更新单个栏目
		 * @param column
		 * @return
		 * @throws GlobalServiceException
		 */
		@Override
		public int update(Column column) throws GlobalServiceException {

				return columnMapper.updateById(column);

		}


		@Override
		public ResponseData removeByIds(String ids) {
				String[] columnIds = ids.split(",");
				boolean flag = this.removeByIds(Arrays.asList(columnIds));
				if (flag) {
						return ResponseData.success();
				} else {
						throw new GlobalServiceException(ResultCodeEnum.DATABASE_OPERATE_EXCEPTION.getCode(), "删除栏目：" + Arrays.asList(columnIds).toString() + ResultCodeEnum.DATABASE_OPERATE_EXCEPTION.getMessage());
				}
		}

}
